/**
 * 邮箱service实现类
 */
package com.bys.ots.service.impl;

import javax.mail.internet.MimeMessage;

import com.bys.ots.dao.EmailMapper;
import com.bys.ots.dao.SoInfoMapper;
import com.bys.ots.dao.UserMapper;
import com.bys.ots.model.SoInfo;
import com.bys.ots.model.User;
import com.bys.ots.pojo.Result;
import com.bys.ots.pojo.ResultUtil;
import com.bys.ots.service.ComplaintService;
import com.bys.ots.service.ISoInfoService;
import com.bys.ots.service.UserService;
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.service.item.EmailMessage;
import microsoft.exchange.webservices.data.credential.ExchangeCredentials;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.property.complex.MessageBody;
import org.springframework.util.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import com.bys.ots.config.RedisExceptionCache;
import com.bys.ots.handler.exception.BusinessException;
import com.bys.ots.handler.exception.RedisConnectionException;
import com.bys.ots.pojo.ConstantModel;
import com.bys.ots.pojo.ResultEnum;
import com.bys.ots.util.redis.RedisUtil;

import net.sf.json.JSONObject;

import com.bys.ots.service.MailService;
import com.bys.ots.util.MailUtil;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author bairuihua
 * 2019/11/26
 */
@Service("mailService")
public class MailServiceImpl implements MailService {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${spring.mail.username}")
    private String from;
    @Value("${spring.mail.password}")
    private String password;
    @Value("${spring.mail.host}")
    private String host;
    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    ConstantModel constantModel;
    @Autowired
    SoInfoMapper soInfoMapper;
    @Autowired
    ISoInfoService iSoInfoService;
    @Autowired
    UserMapper userMapper;
    @Autowired
    EmailMapper emailMapper;

    @Override
    public Result sendVerifyCode(String email) {

        JSONObject jsonObj = JSONObject.fromObject(email);
        email = jsonObj.getString("email");
        email = email.replaceAll("\"", "");
        if (StringUtils.isEmpty(email)) {
            logger.error("->email is empty! the email address is：" + email);
            return ResultUtil.error(ResultEnum.CODE_400);
        }
        MailUtil mutil = new MailUtil();
        String checkCode = mutil.getRandomCode();
        try {
            sendVerificationMail(email, "Thermo Fisher System Verification Code", checkCode);
            try {
                redisUtil.set(email, checkCode, 0);
                Long resExpire = redisUtil.expire(email, 3600, 0);
            } catch (RedisConnectionException e) {
                //如果Redis异常，将验证码存入内存中
                if (RedisExceptionCache.backMap.size() >= 1000) {
                    RedisExceptionCache.backMap.clear();
                }
                RedisExceptionCache.backMap.put(email, checkCode);
            }

            logger.info(email + "发送的验证码为：{}", checkCode);
        } catch (Exception e) {
            logger.error("->验证码发送环节失败！！！验证码为： " + checkCode);
            return ResultUtil.error(ResultEnum.CODE_401);
        }
        return ResultUtil.success();
    }

    public void sendVerificationMail(String to, String title, String code) {
        try {
            sendEmail(constantModel.getVerificationEmailHeader(), constantModel.getVerificationEmailBody(), to, title, code);
            logger.info("验证码邮件发送成功！");
        } catch (Exception e) {
            logger.info("异常信息：" + e);
        }
    }
    public   void sendEmail(String header, String body, String to, String title, String code) {

        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);

        ExchangeCredentials credentials = new WebCredentials(from,password);
        service.setCredentials(credentials);
        try{
            service.setUrl(new URI("https://"+host+"/ews/Exchange.asmx"));
// service.autodiscoverUrl("emailAddress");
            EmailMessage msg= new EmailMessage(service);
//主题
            msg.setSubject(title);
//html
            msg.setBody(MessageBody.getMessageBodyFromText(header + code + body));
            msg.getToRecipients().add(to);
            msg.send();
        }catch(Exception e){
            logger.info("tfs发送邮件异常信息：" + e);
            e.printStackTrace();
        }


    }


//    public void sendEmail(String header, String body, String to, String title, String code) {
//
//        try {
//            MimeMessage mimeMessage = mailSender.createMimeMessage();
//            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
//            messageHelper.setFrom(from);
//            messageHelper.setSubject(title);
//            messageHelper.setTo(to);
//            messageHelper.setText(
//                    header + code + body, true);
//            mailSender.send(mimeMessage);
//        } catch (Exception e) {
//            logger.info("异常信息：" + e);
//        }
//    }

    public void sendComplaintEmail(String to, String title, String so, String userId, String type, String description) {
        try {
            List soList = new ArrayList();
            soList.add(so);
            List<SoInfo> soInfoList = soInfoMapper.selectBySO(so, null);
            //List<SoInfo> soInfoList = soInfoMapper.selectBySO(null, soList, null, null, null, null, null, null, null, null, null, null, null, 0, 1);
            List<Map> saleList = iSoInfoService.getSaleList(soInfoList.get(0), soInfoList);
            List<Map> csrList = iSoInfoService.getCsrList(soInfoList.get(0), soInfoList);
            User user = userMapper.findByUserId(userId);
            String detail = "有一位用户 正在反馈该订单:" + so + " ,反馈内容是:\"" + type + "\"。用户备注内容是:" + description;
            String custom = " 客户信息<br>姓名:" + user.getUserName() + "<br>联系方式:" + user.getTelephone() + "<br>公司名称:" + "" + "<br>邮箱:" + emailMapper.findByUserId(userId).get(0).getEmail();
            String salePersonPhone = "";
            String salePersonEmail = "";
            String csrPhone = "";
            String csrEmail = "";
            if (!ObjectUtils.isEmpty(saleList)) {
                for (int i = 0; i < saleList.size(); i++) {
                    if (StringUtils.isNotEmpty(saleList.get(i).get("salePersonPhone").toString())) {
                        if (StringUtils.isNotEmpty(salePersonPhone) && !salePersonPhone.endsWith(",")) {
                            salePersonPhone = salePersonPhone + "," + saleList.get(i).get("salePersonPhone").toString();
                        } else {
                            salePersonPhone = saleList.get(i).get("salePersonPhone").toString();
                        }
                    }
                    if (StringUtils.isNotEmpty(saleList.get(i).get("salePersonEmail").toString())) {
                        if (StringUtils.isNotEmpty(salePersonEmail) && !salePersonEmail.endsWith(",")) {
                            salePersonEmail = salePersonEmail + "," + saleList.get(i).get("salePersonEmail").toString();
                        } else {
                            salePersonEmail = saleList.get(i).get("salePersonEmail").toString();
                        }
                    }
                }
            }
            if (!ObjectUtils.isEmpty(csrList)) {
                for (int i = 0; i < csrList.size(); i++) {
                    if (StringUtils.isNotEmpty(csrList.get(i).get("csrPhone").toString())) {
                        if (StringUtils.isNotEmpty(csrPhone) && !csrPhone.endsWith(",")) {
                            csrPhone = csrPhone + "," + csrList.get(i).get("csrPhone").toString();
                        } else {
                            csrPhone = csrList.get(i).get("csrPhone").toString();
                        }
                    }
                    if (StringUtils.isNotEmpty(csrList.get(i).get("csrEmail").toString())) {
                        if (StringUtils.isNotEmpty(csrEmail) && !csrEmail.endsWith(",")) {
                            csrEmail = csrEmail + "," + csrList.get(i).get("csrEmail").toString();
                        } else {
                            csrEmail = csrList.get(i).get("csrEmail").toString();
                        }
                    }
                }
            }
            String theo = "赛默飞联系人信息<br>销售电话:" + salePersonPhone + "<br>销售邮箱:" + salePersonEmail + "<br>CSR电话:" + csrPhone + "<br>CSR邮箱:" + csrEmail;
            sendEmail(constantModel.getComplaintEmailHeader(), detail + constantModel.getComplaintEmailBody1() + custom + constantModel.getComplaintEmailBody2() + theo + constantModel.getComplaintEmailBody3(), to, title, "");
            logger.info("投诉邮件发送成功！");
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("异常信息：" + e);
        }
    }
}
